<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class FilterController extends Controller
{
    /**
		* 词语过滤列表
	*/
   public function getIndex(Request $request)
   {
   		$tiao = $request -> input('tiao', '10');
   		$search = $request -> input('search', '');
   		$s = DB::table('shop_filters') -> where('oldWord','like', '%'.$search.'%')->paginate($tiao);
   		// dd($s);
   		$count = DB::table('shop_filters') -> where('oldWord','like', '%'.$search.'%') -> count();
   		$page = $request -> input('page', 1);

        return view('/admin/filter/index', ['data' => $s, 'request' => $request -> all(), 'count' => $count, 'i' => 1 + 1 * $tiao * ($page - 1)]);
   }

    /**
		* 词语过滤添加页面
	*/ 
   public function getAdd()
   {
        return view('/admin/filter/add');
   }

    /**
		* 词语过滤处理添加数据
	*/
	public function postInsert(Request $request)
	{
		//接收form表单的值 并进行验证    
         $this -> validate($request,[
            'oldWord' => 'required',
            'newWord' => 'required',
            'status' => 'required',

        ],[
            'oldWord.required' => '被替换词语名称不能为空',
            'newWord.required' => '替换词语名称不能为空',
            'status.required' => '替换词语状态不能为空',
        ]);
         $s = $request -> only(['oldWord', 'newWord', 'status']);
         $t = DB::table('shop_filters') -> where('oldWord',$s['oldWord']) -> first();
         if ($t){
         	return back() -> withInput() -> with('error', '此词语过滤已存在');
         	exit;
         }
         $s['ctime'] = time();
         $res = DB::table('shop_filters') -> insert($s);
         if ($res) {
         	return redirect('/admin/filter/index') -> with('success', '添加成功');
         } else {
         	return back() -> withInput() -> with('error', '添加失败');
         }

	}

	/**
		* 词语过滤处理删除数据
	*/
	public function getDelete($id)
	{
		$res = DB::table('shop_filters') -> where('id', $id) -> delete();
		if ($res) {
			return redirect('/admin/filter/index?page='.$_GET['page'].'&tiao='.$_GET['tiao'].'&search='.$_GET['search'])-> with('success', '删除成功');
		} else {
			return back() -> with('error', '删除失败');
		}
	
	}

	/**
		* 词语过滤显示修改数据
	*/
	public function getEdit($id)
	{
		$info = DB::table('shop_filters') -> where('id', $id) -> first();
		if ($info) {
			// dd($info);
			return view('/admin/filter/edit',['data' => $info]);
		}
	}

	/**
		* 词语过滤处理修改数据
	*/
	public function postDoedit(Request $request)
	{
         $s = $request -> only(['oldWord', 'newWord', 'status']);	
         $res = DB::table('shop_filters') -> where('id',$request -> input('id')) -> update($s);
         if ($res) {
         	return redirect('/admin/filter/index'.$request -> input('can')) -> with('success', '编辑成功');
         } else {
         	return back() -> withInput() -> with('error', '编辑失败');
		}
	}
}
